package com.yt.file.common.utils;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * FastDFS客户端工具类
 */
@Component
public class FastDFSClient {
    private static final Logger logger = LoggerFactory.getLogger(FastDFSClient.class);

    /**
     * 上传文件
     * @param file 上传的文件
     * @return 返回文件的URL
     */
    public String uploadFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
            byte[] fileBytes = file.getBytes();

            // 创建TrackerClient和TrackerServer
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            try {
                // 获取StorageServer和StorageClient
                StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
                StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

                // 设置元数据
                NameValuePair[] metaList = new NameValuePair[1];
                metaList[0] = new NameValuePair("fileName", fileName);

                // 上传文件
                String fileId = storageClient.upload_file1(fileBytes, extName, metaList);
                logger.info("文件上传成功，fileId: {}", fileId);
                return fileId;
            } finally {
                // 关闭连接
                if (trackerServer != null) {
                    try {
                        trackerServer.close();
                    } catch (IOException e) {
                        logger.error("关闭TrackerServer失败", e);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 下载文件
     * @param fileId 文件ID
     * @return 文件字节数组
     */
    public byte[] downloadFile(String fileId) {
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            try {
                StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
                StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

                return storageClient.download_file1(fileId);
            } finally {
                if (trackerServer != null) {
                    trackerServer.close();
                }
            }
        } catch (Exception e) {
            logger.error("文件下载失败", e);
            throw new RuntimeException("文件下载失败", e);
        }
    }

    /**
     * 删除文件
     * @param fileId 文件ID
     */
    public void deleteFile(String fileId) {
        try {
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            try {
                StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);
                StorageClient1 storageClient = new StorageClient1(trackerServer, storageServer);

                storageClient.delete_file1(fileId);
                logger.info("文件删除成功，fileId: {}", fileId);
            } finally {
                if (trackerServer != null) {
                    trackerServer.close();
                }
            }
        } catch (Exception e) {
            logger.error("文件删除失败", e);
            throw new RuntimeException("文件删除失败", e);
        }
    }
}